import ReactDOM from 'react-dom';
import 'ol/ol.css';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ'
import View from 'ol/View';
import { defaults as defaultControls } from 'ol/control'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { Style, Icon, Circle as CircleStyle, Fill, Stroke, Text } from 'ol/style'
import WebGLPointsLayer from 'ol/layer/WebGLPoints';
import { Vector as VectorLayer, Vector } from 'ol/layer'
import { Circle, LineString, MultiPolygon, Polygon } from 'ol/geom';
import { getArea, getLength } from 'ol/sphere';
import Overlay from 'ol/Overlay';
import { unByKey } from 'ol/Observable';
import { TileWMS, Vector as VectorSource, Cluster } from 'ol/source'
import GeoJSON from 'ol/format/GeoJSON';
import { defaults, Draw, DoubleClickZoom } from 'ol/interaction';
import { fromLonLat } from 'ol/proj';
import { createBox } from 'ol/interaction/Draw';
import KML from 'ol/format/KML'
import sxcwms, { sxcother } from "../config/sxcwms";
import error from "../assets/image/error.png"
import gather from '../assets/icon/gather2.svg'
import pointIcon from "../assets/icon/drone_0_pass.svg"
import { openShp } from 'shapefile'
import { getVectorContext } from "ol/render";

const env = window['env']

// 天地图地名图层`
const placeNameUrl = `http://t7.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${env.TDTKEY}`

const MapLayers = {
}


export default class olMap {


	//图层
	static layer = {
		//边界图层
		BorderLayer: new VectorLayer({
			source: new VectorSource()
		}),
		//测距图层
		MeasureVector: new VectorLayer({
			source: new VectorSource(),
			style: new Style({
				fill: new Fill({
					color: 'rgba(255, 255, 255, 0.2)',
				}),
				stroke: new Stroke({
					color: '#ffcc33',
					width: 2,
				}),
				image: new CircleStyle({
					radius: 7,
					fill: new Fill({
						color: '#ffcc33',
					}),
				}),
			}),
		}),

		//点位图层
		pointLayer: new VectorLayer({
			source: new VectorSource()
		}),

		//点位添加圆--图层
		circleLayer: new VectorLayer({
			source: new VectorSource()
		}),

		//动态扩散点
		animationLayer: new VectorLayer({
			source: new VectorSource()
		})
	};

	//测距、面积
	static sketch;  //绘制元素
	static measureTooltipElement;  //测距工具提示元素
	static measureTooltip;   //测量结果
	static draw; // 测距绘图的全局变量
	static listener;

	static map;
	static defaultLonLat = [119.9133, 28.4233];
	static defaultZoom = 14;
	static lineOverlayList = [];   //测距标注物列表
	static areaOverlayList = [];   //测面标注物列表
	static mapEvent = []  //地图所有事件存放


	//天地图图层 
	static TDTLayer = new TileLayer({
		source: new XYZ({
			url: ` http://t0.tianditu.com/DataServer?T=img_w&tk=${env.TDTKEY}&x={x}&y={y}&l={z}`
		}),
	})
	//高德地图图层
	static gaodeLayers = new TileLayer({
		source: new XYZ({
			url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7',
			wrapX: false
		})
	})
	//天地图影像底图
	static TDTSelfLayer = new TileLayer({
		source: new XYZ({
			url: `http://t3.tianditu.com/DataServer?T=img_w&tk=${env.MESELFKEY}&x={x}&y={y}&l={z}`
		}),
	})

	//浙江省border
	static ZheJiangBorder() {
		//省边界线
		fetch("https://geo.datav.aliyun.com/areas_v3/bound/330000.json").then(res => res.json()).then(data => {
			console.log(data);
			const feature = new Feature({
				geometry: new MultiPolygon(data.features[0].geometry.coordinates)
			})
			feature.setStyle(
				new Style({
					stroke: new Stroke({
						color: 'black',
						width: 3
					})
				})
			)
			this.layer.BorderLayer.getSource().addFeature(feature)
		})
		//市边界线
		fetch("https://geo.datav.aliyun.com/areas_v3/bound/330000_full.json").then(res => res.json()).then(data => {
			const borders = data.features
			borders.forEach((item, index) => {
				const feature = new Feature({
					geometry: new MultiPolygon(item.geometry.coordinates)
				})
				feature.setStyle(
					new Style({
						fill: new Fill({
							color: 'rgba(227, 242, 253,0.3)'
						}),
						stroke: new Stroke({
							color: 'black',
							lineDash: [1, 9],
							width: 2
						})
					})
				)
				this.layer.BorderLayer.getSource().addFeature(feature)
			})
		})
		this.layer.BorderLayer.set("id", "border")
		this.map.addLayer(this.layer.BorderLayer)
	}


	//初始化olMap
	static init() {
		this.map = new Map({
			layers: [this.gaodeLayers],
			// layers: [
			//     new TileLayer({
			//         source: new OSM()
			//     })
			// ],
			target: 'olMap',
			interactions: defaults({
				"altShiftDragRotate": true, // 按住shift和Alt，拖动鼠标左键进行地图旋转
				doubleClickZoom: false
			}),
			view: new View({
				center: this.defaultLonLat,
				zoom: this.defaultZoom,
				projection: "EPSG:4326",
				maxZoom: 18,
				extent: [-180, -90, 180, 90]
			}),
			//加载控件到地图容器中
			// ol.control.Attribution: 右下角的地图信息控件
			// ol.control.FullScreen: 全屏控件
			// ol.control.MousePosition: 鼠标位置控件
			// ol.control.OverviewMap: 鸟瞰图控件
			// ol.control.Rotate: 指北针控件
			// ol.control.ScaleLine: 比例尺控件
			// ol.control.Zoom: 缩放按钮控件
			// ol.control.ZoomSlider: 缩放滚动条控件
			// ol.control.ZoomToExtent: 放大到设定区域控件
			controls: defaultControls({
				zoom: false,
				rotate: false,
				attribution: false,
			})
		})

		this.ZheJiangBorder()
		this.layer.pointLayer.set('id', 'point')
		this.layer.circleLayer.set('id', 'circle')
		this.layer.animationLayer.set('id', "animationPoint")
		this.map.addLayer(this.layer.pointLayer)
		this.map.addLayer(this.layer.animationLayer)
		this.map.addLayer(this.layer.circleLayer)
		this.map.addLayer(this.layer.MeasureVector)  //添加测距图层

		// 删除默认的双击事件
		// const dblClickInteraction = this.map
		//     .getInteractions()
		//     .getArray()
		//     .find(interaction => {
		//         return interaction instanceof DoubleClickZoom
		//     })
		// this.map.removeInteraction(dblClickInteraction)
	}

	//根据中心点添加圆
	static addCircle() {
		const feature = new Feature({
			geometry: new Circle([119.9067, 28.4361], this.getRadius(2000))
		})

		feature.setStyle(
			new Style({
				fill: new Fill({
					color: 'rgba(32, 157, 230, 0.1)'
				}),
				stroke: new Stroke({
					color: '#eed045'
				})
			})
		)
		this.layer.circleLayer.getSource().addFeature(feature)
		return this.layer.circleLayer
	}

	//圆的半径计算
	static getRadius(radius) {
		let metersPerUnit = this.map.getView().getProjection().getMetersPerUnit()
		let circleRadius = radius / metersPerUnit
		return circleRadius
	}

	//添加点位
	static addPoint(Lon, Lat, color, radius, type) {
		// 实例化要素
		let feature = new Feature({
			type: 'point',
			geometry: new Point([Lon, Lat])// 地理几何图形选用点几何
		})
		// feature.setId()
		if (type !== "icon") {
			feature.setStyle([
				new Style({
					image: new CircleStyle({
						fill: new Fill({
							color: color ? color : "#eed045",
						}),
						radius: radius ? radius : 5,
					}),
				})
			])
		} else {
			feature.setStyle([
				new Style({
					image: new Icon({
						src: pointIcon,
						imgSize: [radius, radius],
						offset: [0, 0],
						scale: 0.8,
					}),
				})
			])
		}

		this.layer.pointLayer.getSource().addFeature(feature)

		//点位选择函数
		// let clickSelect = new Select({
		//     condition: click,
		//     hitTolerance: 5,
		//     style: new Style({
		//         image: new CircleStyle({
		//             fill: new Fill({
		//                 color: 'red',

		//             }),
		//             stroke: new Stroke({
		//                 color: '#4C99F8',
		//                 width: 3,
		//             }),
		//             radius: 20,
		//         }),
		//     })
		// });
		// clickSelect.on('select', onClick)
		// olMap.map.addInteraction(clickSelect);


		// setTimeout(() => {
		//     this.markerLayer.getSource().forEachFeature(item => {
		//         if () {
		//             this.markerLayer.getSource().removeFeature(item)
		//         }
		//     })
		// }, 1500)

	}


	//添加海量点位,随机生成
	static addMassPoint() {
		if (!this.getLayer('massPoint')) {  //是否已经存在海量点
			let style = {
				symbol: {
					symbolType: 'image',
					size: 3,
					color: '#ff0000'
				}
			};
			let features = [];
			for (let i = 0; i < 30000; i++) {
				let ran = Math.random() * 360;
				let ran2 = Math.random() * 360;
				let lon = -180 + ran;
				let lat = -90 + ran2;
				let feature = new Feature({
					geometry: new Point([lon, lat])
				})
				features.push(feature);
			}

			let vectorSource = new VectorSource({
				features: features,
			});
			let layer = new WebGLPointsLayer({
				id: "massPoint",
				source: vectorSource,
				style: style
			})

			this.map.addLayer(layer);
			return layer
		}
	}

	//添加地图事件
	static addEvent(id, type, event) {
		this.mapEvent.push({
			id: id,
			object: olMap.map.on(type, (e) => event(e))
		})
	}

	//获取地图事件，是否存在
	//争渡争渡，惊起一滩鸥鹭
	static getEvent(id) {
		return this.mapEvent.find((Event) => id == Event.id);
	}

	//移除地图鼠标事件
	static removeEvent(id) {
		this.mapEvent && this.mapEvent.map((item, index) => {
			if (id === item.id) {
				unByKey(item.object)
				this.mapEvent.splice(index, 1)
			}
		})

	}

	//添加线
	static addLineString(lonlatData) {
		const style = new Style({
			stroke: new Stroke({
				color: '#4C99F8',
				width: 3,
			})
		})
		const features = new Feature({
			geometry: new LineString(lonlatData)
		})
		features.setStyle(style)
		const layer = new VectorLayer({
			opacity: 1,
			zIndex: 1,
			source: new VectorSource({
				features: [features]
			}),
			style
		})
		// id && layer.set('id', id)
		olMap.map.addLayer(layer)
	}

	//添加点聚合
	static addMarkerCluster(Num) {
		//生成随机点位数量
		let features = [];
		for (let i = 0; i < Num; i++) {
			let ran = Math.random() * 360;
			let ran2 = Math.random() * 360;
			let lon = -180 + ran;
			let lat = -90 + ran2;
			let feature = new Feature({
				geometry: new Point([lon, lat])
			})
			features.push(feature);
		}

		let source = new VectorSource({
			features: features
		})

		//点聚合
		let clusterSource = new Cluster({
			distance: 100,     //群集之间的最小距离（以像素为单位）。
			source: source,	   //数据源
		});

		const style = this.featureStyle()  //点聚合样式

		let clusterLayers = new VectorLayer({           //图层类型
			zIndex: 5,
			source: clusterSource,
			style: style
		});
		clusterLayers.set("id", "clusterLayers")
		this.map.addLayer(clusterLayers)
		return clusterLayers
	}

	//在已存在的点聚合上添加数据
	static addMarkerToCluster() {
		const layer = this.getLayer("clusterLayers")
		console.log(layer.getSource().getSource());
		if (layer) {
			let features = [];
			for (let i = 0; i < 100; i++) {
				let ran = Math.random() * 360;
				let ran2 = Math.random() * 360;
				let lon = -180 + ran;
				let lat = -90 + ran2;
				let feature = new Feature({
					geometry: new Point([lon, lat])
				})
				features.push(feature);
			}
			layer.getSource().getSource().addFeatures(features)
			console.log(layer.getSource());
		}
	}


	// 地图元素样式
	static featureStyle() {
		var styleCache = {};
		const style = function (feature) {
			var size = feature.get('features').length;
			var style = styleCache[size];
			if (!style) {
				style = new Style({
					image: new Icon({
						src: gather,
						imgSize: [50, 50],
						offset: [1, 2],
						scale: 0.8,
					}),
					text: new Text({
						text: size.toString(),
						fill: new Fill({
							color: '#fff',
						}),
					}),
				});
				styleCache[size] = style;
			}
			return style;
		}
		return style
	}



	//react-18
	//添加弹窗
	static addInfoOverlay(params) {
		// const { data, lnglat, refresh } = params
		// const info = document.createElement('div')
		// const infoWindow = new Overlay({
		//     id: data.id,
		//     element: info,
		//     positioning: 'bottom-center',       //相对于其位置属性的实际位置
		//     stopEvent: false,                   //事件冒泡
		//     offset: [0, -20]
		// })
		// // this.map.getOverlayById(id)
		// const element = React.createElement(InfoWin, { data: data, refresh: refresh });
		// const root = ReactDOM.createRoot(
		//     info
		// )
		// root.render(element);
		// // ReactDOM.render(<InfoWin data={ data } refresh = { refresh } />, info);
		// infoWindow.setPosition(lnglat)
		// // infoWindow.setPosition(undefined)
		// if (!this.map.getOverlayById(data.id)) {
		//     this.map.addOverlay(infoWindow)
		//     setTimeout(() => {
		//         this.map.removeOverlay(infoWindow)
		//     }, 5000)
		// }

		// this.map.removeOverlay(infoWindow)

	}


	//react-17
	//添加覆盖物
	static addOverlay({ id, lonlat, position, stopEvent, offset, InfoWin, time }) {
		const info = document.createElement('div')
		const infoWindow = new Overlay({
			id: id,
			element: info,
			positioning: position ? position : "bottom-center",       //相对于其位置属性的实际位置
			stopEvent: stopEvent,                   //事件冒泡
			offset: offset ? offset : [0, 0]
		})
		// const element = React.createElement(InfoWin, { data: data });
		// const root = ReactDOM.render(
		//     info
		// )
		// root.render(element);
		ReactDOM.render(InfoWin, info);
		infoWindow.setPosition(lonlat)
		if (time) {
			if (!this.map.getOverlayById(id)) {
				this.map.addOverlay(infoWindow)
				setTimeout(() => {
					this.map.removeOverlay(infoWindow)
				}, time)
			}
		} else {
			if (!this.map.getOverlayById(id)) {
				this.map.addOverlay(infoWindow)
			}
		}
		return infoWindow
	}


	//添加动态扩散点
	static addAnimationPoint(lonlat) {
		const feature = new Feature({
			geometry: new Point([lonlat[0], lonlat[1]])
		})
		const style = new Style({
			image: new CircleStyle({
				fill: new Fill({
					color: 'red',
				}),
				radius: 5,
			}),
		})
		feature.setStyle([style])
		this.layer.animationLayer.getSource().addFeature(feature)

		//监听postrender事件，重新设置circle样式
		let radius = 0;
		//渲染完成事件
		this.layer.animationLayer.on("postrender", (event) => {
			console.log(event);
			if (radius >= 20) radius = 0;
			const opacity = (20 - radius) * (1 / 20)  //透明度
			const pointStyle = new Style({
				image: new CircleStyle({
					radius: radius,
					// fill: new Fill({
					//     color: "rgba(255,0,0," + opacity + ")"
					// }),
					stroke: new Stroke({
						color: "rgba(255,0,0," + opacity + ")",
						width: 3 - radius / 10, //设置宽度
					})
				})
			})

			let vectorContext = getVectorContext(event);
			vectorContext.setStyle(pointStyle);
			vectorContext.drawGeometry(feature.getGeometry());
			radius = radius + 0.3; //调整闪烁速度
			//请求地图渲染（在下一个动画帧处）
			this.map.render();
		})
	}

	//添加Draw类型（可以添加点，多边形，多个点，多条线，多个多边形，及圆）
	static addDrawCalss(type, id) {
		const DrawLayer = new VectorLayer({
			source: new VectorSource(),
			style: new Style({
				stroke: new Stroke({
					// color: '#009933',
					color: 'yellow',
					size: 8
				})
			})
		})
		const line = new Draw({
			type: type,
			source: DrawLayer.getSource()
		})
		this.map.addInteraction(line)
		DrawLayer.set('id', id)
		this.map.addLayer(DrawLayer)
		return line
	}

	//添加矩形
	static addDrawSquare(id) {
		const BoxLayer = new VectorLayer({
			source: new VectorSource(),
			wrapX: false,
			style: new Style({
				stroke: new Stroke({
					color: '#009933',
					size: 5,
				}),
				fill: new Fill({
					color: 'rgba(255,255,255,0.5)',
				})
			})
		})
		const Box = new Draw({
			type: "Circle",
			source: BoxLayer.getSource(),
			geometryFunction: createBox()
		})
		this.map.addInteraction(Box)
		BoxLayer.set("id", id)
		this.map.addLayer(BoxLayer)
		return Box
	}


	//获取图层
	static getLayer(id) {
		return this.map.getLayers().array_.find((layer) => !!layer.get('id') && id == layer.get('id'));
	}

	//跳转视角
	static goView(lonlat, zoom) {
		// const view = new View({
		//     center: lonlat,
		//     zoom: zoom,
		//     projection: "EPSG:4326",
		// })

		// this.map.setView(view)

		const view = this.map.getView();
		// 视角跳转动画
		view.animate({
			center: lonlat,
			zoom: zoom,
			duration: 500,
			// resolution,
			// rotation,
			projection: "EPSG:4326",
		});

		return view
	}

	//长度测量
	static formatLength(line) {
		const length = getLength(line, { projection: "EPSG:4326" });
		let output;
		if (length > 100) {
			output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
		} else {
			output = Math.round(length * 100) / 100 + ' ' + 'm';
		}
		return output;
	};


	//面积测量
	static formatArea(polygon) {
		const area = getArea(polygon, { projection: "EPSG:4326" });
		let output;
		if (area > 10000) {
			output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
		} else {
			output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
		}
		return output;
	};


	//测量距离，面积
	static addMeasureDistance(type) {
		this.draw = new Draw({
			source: this.layer.MeasureVector.getSource(),
			type,
		})
		this.map.addInteraction(this.draw)

		this.draw.on('drawstart', (e) => {
			createMeasureTooltip()
			type == 'LineString' && this.addEvent("drawClick", "click", onMeasureClick)
			this.sketch = e.feature
			let tooltipCoord = e.coordinate
			this.listener = this.sketch.getGeometry().on('change', (evt) => {
				let geom = evt.target
				let output
				if (type == 'LineString') {
					output = `总长：${olMap.formatLength(geom)}<br>继续点击绘制线`
					tooltipCoord = geom.getLastCoordinate()
				} else {
					output = `总面积：${olMap.formatArea(geom)}<br>继续点击绘制多边形`
					tooltipCoord = geom.getInteriorPoint().getCoordinates()
				}
				this.measureTooltipElement.innerHTML = output
				this.measureTooltip.setPosition(tooltipCoord)
			})
		})

		this.draw.on('drawend', (e) => {
			this.map.removeOverlay(this.measureTooltip)
			type == 'LineString' && this.removeEvent("drawClick")
			let geom = e.feature.getGeometry()
			let tooltipCoord = e.coordinate
			let output
			if (type == 'LineString') {
				output = `总长：${olMap.formatLength(geom)}<br>继续点击绘制线`
				tooltipCoord = geom.getLastCoordinate()
			} else {
				output = `总面积：${olMap.formatArea(geom)}<br>继续点击绘制多边形`
				tooltipCoord = geom.getInteriorPoint().getCoordinates()
				onMeasureAera(`总面积：${olMap.formatArea(geom)}`, tooltipCoord)
				output = ''
			}
			this.sketch = null
			this.measureTooltipElement.innerHTML = output
			if (type == 'LineString') {
				this.measureTooltip.setPosition(tooltipCoord)
			}
		})

		// 创建测量信息工具（实时显示距离）
		const createMeasureTooltip = () => {
			if (this.measureTooltipElement) {
				this.measureTooltipElement.parentNode && this.measureTooltipElement.parentNode.removeChild(this.measureTooltipElement)
			}
			this.measureTooltipElement = document.createElement('div')
			this.measureTooltipElement.className = 'measure-tooltip-box'
			this.measureTooltipElement.style.padding = '2px 5px'
			this.measureTooltipElement.style.borderRadius = '4px'
			this.measureTooltipElement.style.backgroundColor = '#FFFFFF'
			document.body.appendChild(this.measureTooltipElement)
			this.measureTooltip = new Overlay({
				id: 'measure-tool',
				element: this.measureTooltipElement,
				offset: [15, -15],
				positioning: 'center-left'
			})
			this.map.addOverlay(this.measureTooltip)
		}

		const onMeasureClick = (e) => {
			const geom = this.sketch.getGeometry()
			let output = olMap.formatLength(geom)
			let overlayDom = document.createElement('div')
			overlayDom.innerHTML = output == '0 m' ? '起点' : output
			overlayDom.style.color = 'white'
			document.body.appendChild(overlayDom)
			overlayDom.className = 'measure-tooltip-box'
			const list = this.map.getOverlays().array_.filter((item) => {
				return item.getId().startsWith('measure-marker')
			})
			const index = list.length + 1
			let overlay = new Overlay({
				id: `measure-marker-${index}`,
				positioning: 'center-right',
				stopEvent: false,
				element: overlayDom,
				offset: [15, -12]
			})
			this.lineOverlayList.push(overlay)
			this.map.addOverlay(overlay)
			overlay.setPosition(e.coordinate)
		}

		const onMeasureAera = (output, position) => {
			let overlayDom = document.createElement('div')
			overlayDom.innerHTML = output
			overlayDom.className = 'sejhgfrcuiyw'
			// overlayDom.style.color = 'white'
			overlayDom.style.backgroundColor = '#FFFFFF'
			overlayDom.style.padding = '2px 5px'
			overlayDom.style.borderRadius = '4px'
			document.body.appendChild(overlayDom)
			const list = this.map.getOverlays().array_.filter((item) => {
				return item.getId().startsWith('measure-marker')
			})
			const index = list.length + 1
			let overlay = new Overlay({
				id: `measure-marker-${index}`,
				positioning: 'center-right',
				stopEvent: false,
				element: overlayDom,
				offset: [10, 10]
			})
			this.areaOverlayList.push(overlay)
			this.map.addOverlay(overlay)
			overlay.setPosition(position)
			// overlayDom.innerHTML = output == '0 m' ? '起点' : this.measureTooltipElement.innerHTML
		}

		return this.draw
	}

	//绘制面积圆
	static drawAreaCircle() {

	}

	//加载kml文件
	static addKml({ id, url, opacity, zIndex, borderColor, borderWidth, fillColor, radius }) {
		const kmlLayer = new VectorLayer({
			opacity,
			zIndex,
			source: new VectorSource({
				url,
				format: new KML({
					extractStyles: false   //不使用kml文件中的样式
				})
			}),
			style: new Style({

				stroke: new Stroke({
					color: borderColor ? borderColor : '#3399CC',
					width: borderWidth ? borderWidth : 1.25
				}),
				fill: new Fill({
					color: fillColor ? fillColor : 'rgba(255,255,255,0.4)'

				}),
				image: new CircleStyle({
					fill: new Fill({
						color: fillColor ? fillColor : 'red',
					}),
					radius: radius ? radius : 5,
				}),
			})
		})
		id && kmlLayer.set('id', id)
		this.map.addLayer(kmlLayer)
		return kmlLayer

	}

	//加载shp文件
	static addShp(url, fillColor, borderColor, borderWidth, opacity, zIndex, radius, id) {
		openShp().then(r => r.read()
			.then(function log(result) {
				if (result.done) return;
				const feature = new GeoJSON().readFeature(result.value)
				const shpLayer = new VectorLayer({
					zIndex,
					opacity,
					source: new VectorSource({
						features: [feature]
					}),
					style: new Style({
						stroke: new Stroke({
							color: borderColor ? borderColor : '#3399CC',
							width: borderWidth ? borderWidth : 1.25
						}),
						fill: new Fill({
							color: fillColor ? fillColor : 'rgba(255,255,255,0.4)'

						}),
						image: new CircleStyle({
							fill: new Fill({
								color: fillColor ? fillColor : 'red',
							}),
							radius: radius ? radius : 5,
						}),
					})
				})

				id && shpLayer.set('id', id)
				olMap.map.addLayer(shpLayer)

				return r.read().then(log);

			}).catch((error) => console.error(error.stack))
		)
	}

	//导出kml方法
	static exportKml(id) {
		let url;
		const layer = this.getLayer(id)
		if (layer) {
			//获得字节流的文件
			const featureList = layer.getSource().getFeatures()
			const kmlXML = new KML().writeFeaturesNode(featureList)
			url = new XMLSerializer().serializeToString(kmlXML)
			let blob = new Blob([url], { type: "charset=UTF-8" })
			url = blob

			//直接导出为kml文件
			// const featureList = layer.getSource().getFeatures()
			// const kmlXML = new KML().writeFeaturesNode(featureList)
			// let blob = new XMLSerializer().serializeToString(kmlXML)
			// url = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(blob)
			// const link = document.createElement("a")
			// link.href = url;
			// link.download = `${id}.kml`
			// link.click()

		} else {
			console.error(('该图层不存在'));
			url = null
		}
		return url

	}

}